const db = require('../core/mysql/db.js')
const ApiResponseUtil = require('../util/ApiResponseUtil.js')

// 好友关系列表 (状态：• 0-待确认（好友请求）• 1-已同意（互为好友）• 2-已拒绝 • 3-已拉黑 • 4-已删除)
exports.handleFriendshipList = async (req, res) => {
    const { status, nickname = '' } = req.query
    const uid = req.auth.id

    let sender = `
            -- 我是发送方（我发起了好友关系，对方是接收者）
            SELECT 
                f.id,
                f.uid AS sender_id,           -- 我（发送方）
                f.tid AS receiver_id,         -- 对方（接收方）
                u.id AS other_user_id,
                u.nickname AS other_user_nickname,
                u.avatar AS other_user_avatar,
                f.status,
                f.create_at,
                f.update_at,
                'sender' AS direction         -- 表示我是发送方
            FROM friendship f
            INNER JOIN users u ON f.tid = u.id
            WHERE f.uid = ? AND f.status = ?
    `
    let receiver = `
            UNION ALL

            -- 我是接收方（别人发起的好友关系，我是接收者）
            SELECT 
                f.id,
                f.uid AS sender_id,           -- 对方（发送方）
                f.tid AS receiver_id,         -- 我（接收方）
                u.id AS other_user_id,
                u.nickname AS other_user_nickname,
                u.avatar AS other_user_avatar,
                f.status,
                f.create_at,
                f.update_at,
                'receiver' AS direction       -- 表示我是接收方
            FROM friendship f
            INNER JOIN users u ON f.uid = u.id
            WHERE f.tid = ? AND f.status = ? 
    `

    let sql = sender + receiver

    if (nickname != null && nickname.trim() !== '') {
        sender += ` AND u.nickname LIKE '%${nickname}%'`
        receiver += ` AND u.nickname LIKE '%${nickname}%'`
        sql = sender + receiver
    }

    const [result] = await db.query(sql, [uid, status, uid, status])

    if (result.length === 0) {
        return res.send(ApiResponseUtil.success(200, `暂无好友关系！`, []))
    } else {
        return res.send(ApiResponseUtil.success(200, '好友关系列表获取成功！', result))
    }
}

// 好友关系添加
exports.handleFriendshipAdd = async (req, res) => {
    const uid = req.auth.id
    const { tid } = req.body

    if (uid == tid) {
        return res.send(ApiResponseUtil.error(400, '不能添加自己为好友！'))
    }

    if (!tid) {
        return res.send(ApiResponseUtil.error(400, '目标用户ID不能为空！'))
    }

    // 检查是否存在待确认的好友请求（避免重复添加）
    const toBeConfirmed = `
        select id, status from friendship 
        where ((uid = ? and tid = ?) or (uid = ? and tid = ?))
        and status = 0
    `
    const [pending] = await db.query(toBeConfirmed, [uid, tid, tid, uid])

    if (pending.length > 0) {
        return res.send(ApiResponseUtil.error(400, '好友请求已存在，等待对方通过，请勿重复操作！'))
    }

    // 检查是否已经存在好友关系（避免重复添加）
    const agreed = `
        select id, status from friendship 
        where ((uid = ? and tid = ?) or (uid = ? and tid = ?))
        and status = 1
    `
    const [existing] = await db.query(agreed, [uid, tid, tid, uid])

    if (existing.length > 0) {
        return res.send(ApiResponseUtil.error(400, '你们已经是好友了！'))
    }

    // 插入好友请求（status = 0，待确认）
    const insertSql = `
      insert into friendship (uid, tid, status, create_at, update_at) 
      value (?, ?, 0, now(), now())
    `
    const [result] = await db.query(insertSql, [uid, tid])

    if (result.affectedRows === 1) {
        return res.send(ApiResponseUtil.success(200, '好友请求发送成功，请等待对方确认！'))
    } else {
        return res.send(ApiResponseUtil.error(500, '好友请求发送失败！'))
    }
}

// 好友关系更新
exports.handleFriendshipUpdate = async (req, res) => {

    const { tid, status } = req.body
    const uid = req.auth.id

    if (!tid) {
        return res.send(ApiResponseUtil.error(400, '目标用户ID不能为空！'))
    }

    const sql = `
        update friendship set status = ? where uid = ? and tid = ?
    `
    const [result] = await db.query(sql, [status, tid, uid])

    if (result.affectedRows === 1) {
        return res.send(ApiResponseUtil.success(200, '好友关系更新成功！'))
    } else {
        return res.send(ApiResponseUtil.error(500, '好友关系更新失败！'))
    }
}

// 好友关系删除
exports.handleFriendshipDel = async (req, res) => {
    const { tid } = req.body
    const uid = req.auth.id

    if (!tid) {
        return res.send(ApiResponseUtil.error(400, '目标用户ID不能为空！'))
    }

    const del = `DELETE FROM friendship WHERE uid = ? AND tid = ? AND status = 4`

    const [result] = await db.query(del, [uid, tid])

    if (result.affectedRows === 1) {
        return res.send(ApiResponseUtil.success(200, '好友关系删除成功！'))
    } else {
        return res.send(ApiResponseUtil.error(404, '好友关系不存在或已删除！'))
    }
}